<script setup lang="ts">
import {
  ContractTemplateApi,
  ContractTemplateType,
  ContractTemplateVO
} from "@/views/ai/law/api/contracttemplate";
import {useElTableSelector} from "@/components/ATableSelect/f";
import {TableColumn} from "@/components/ATable/types";
import dayjs from "dayjs";
import FormCreate, {Api} from "@form-create/element-ui";
import {BluePrintApi} from "@/views/ai/agent/x6/api/blue-print-api";
import {ToolsProtocol} from "@/views/ai/miuma/chat/data";
import {messageBus} from "@/views/ai/miuma/chat/hook";
import {reactive, ref} from "vue";
import RulesCheckbox from "@/views/ai/miuma/chat/system/components/rulesCheckbox.vue";
import {RuleDetailApi} from "@/views/ai/law/api/ruledetail";


const colums = reactive<TableColumn[]>([
  {
    label: '文件名称',
    prop: 'name',
    useFilter: true,
    fixed: 'left',
    width: '200px',
    queryForms: [
      {
        label: '筛选',
        component: 'ElInput',
        prop: 'name'
      }
    ]
  },
  {
    label: '文件地址',
    width: '200px',
    prop: 'fileUrl',
  },
  {
    label: '规则分组',
    width: '100px',
    prop: 'ruleGroupName'
  },
  {
    label: '文件类型',
    width: '100px',
    prop: 'type',
    //@ts-ignore
    formatter:(row)=>{
      const s = ContractTemplateType.filter(e=>e.value==row.type).map(e=>e.label).join(',');
      return ()=>h('div',{},s)
    }
  },
  {
    label: '创建时间',
    prop: 'createTime',
    width: '100px',
    formatter:(row)=>{
      const s = dayjs(row.createTime).format('YYYY-MM-DD HH:mm:ss');
      return h('div',{},s)
    }
  }
])
const form=reactive<{
  temp?:ContractTemplateVO,
  data?:any,
  checkedRules?:any[]
}>({})
const getRuleGroupDetail = async (groupId: number) => {
  const { list } = await RuleDetailApi.getRuleDetailPage({
    groupId,
    pageNo: 1,
    pageSize: 100,
  });
  rules.value = list;
};
const rules = ref([] as any);
const fcFormOp=ref()
const loading=ref(false);
const onSelected=async (row:any)=>{
  //console.log(row)
  loading.value = true;
  form.temp=row
  //加载对应表格
  if (row.formId){
    fcFormOp.value= await ContractTemplateApi.loadTemplateFrom(row.formId);
  }
  await getRuleGroupDetail(row.ruleGroupId)
  loading.value = false;
}
const onSubmit=async (formData: any, api: Api)=>{
  const map=extractFieldTitleMapping(fcFormOp.value.formConfig)
  const data = replaceJsonKeys(formData,map)
  //先上传文件到阿里云
  const fileUrl = form.temp?.fileUrl as string;
  if (fileUrl){
    const d=await BluePrintApi.uploadFile2(fileUrl,"TongYi")
    const proms=[
      `以下是写作时需要完善的条款:\n${JSON.stringify(form.checkedRules)}\n以上是写作时需要完善的条款`,
      "请以这个文档为模板，进行合同写作。",
      `写作要求参考以下:\n ${JSON.stringify(data)} \n 以上是写作要求`,
    ]
    console.log("ai 提示词",proms)
    ElMessage.success("在写作完成后将自动调整格式!")
    doAutoWrite(d.id as string,proms)
  }
}
const doAutoWrite=(fileId:string,rules:string[])=>{
  const e:ToolsProtocol={
    tools:true,
    component:'DocEditor',
    active:'DoAutoWrite',
    subData:{rules,fileId}
  }
  console.log("doAutoWrite",e)
  messageBus.emit('useTools',e)
}
interface Task{
  rule:any,
  loading: boolean,
  modify?:string,
  source?:string,
  judgement?:string,
  score?:number,
  selected?:boolean
}
function extractFieldTitleMapping(json) {
  const mapping = {};

  // 处理数组类型的JSON
  if (Array.isArray(json)) {
    json.forEach(item => {
      // 如果当前项有field和title属性，添加到映射中
      if (item.field && item.title) {
        mapping[item.field] = item.title;
      }

      // 递归处理所有对象属性和children数组
      Object.values(item).forEach(value => {
        if (value && (typeof value === 'object' || Array.isArray(value))) {
          const childMapping = extractFieldTitleMapping(value);
          Object.assign(mapping, childMapping);
        }
      });
    });
  }
  // 处理对象类型的JSON
  else if (typeof json === 'object' && json !== null) {
    // 如果当前对象有field和title属性，添加到映射中
    if (json.field && json.title) {
      mapping[json.field] = json.title;
    }

    // 递归处理对象的所有属性值
    Object.values(json).forEach(value => {
      if (value && (typeof value === 'object' || Array.isArray(value))) {
        const childMapping = extractFieldTitleMapping(value);
        Object.assign(mapping, childMapping);
      }
    });
  }

  return mapping;
}

function replaceJsonKeys(json, mapping) {
  if (Array.isArray(json)) {
    return json.map(item => replaceJsonKeys(item, mapping));
  }
  if (typeof json === 'object' && json !== null) {
    const result = {};
    for (const [key, value] of Object.entries(json)) {
      const newKey = mapping[key] || key;
      result[newKey] = replaceJsonKeys(value, mapping);
    }
    return result;
  }
  return json;
}

const Selector = useElTableSelector(
  {
    loadFunction:ContractTemplateApi.getContractTemplatePage,
    columns:colums,
    selectType:'radio',
    formart:(d:any)=>{
      return d.name
    }
  }
);
</script>

<template>
  <div class="writing-doc" v-loading="loading">
    <el-form>
      <el-form-item label="模板">
        <Selector.DOM @selected="onSelected"/>
      </el-form-item>
      <el-form-item>
        <div style="max-height: 500px;width: 100%">
          <RulesCheckbox v-model="form.checkedRules" :rules="rules" />
        </div>
      </el-form-item>
      <el-form-item>
        <el-alert type="success">我们将在写作完成后进行格式的调整!</el-alert>
      </el-form-item>
    </el-form>
    <form-create
      v-if="fcFormOp!=undefined"
      :rule="fcFormOp.formConfig"
      :option="fcFormOp.option"
      @submit="onSubmit"
    />
  </div>
</template>

<style scoped lang="scss">
.writing-doc{
  display: flex;
  flex-direction: column;
  gap: 5px;
}
</style>
